package com.sunwoda.demo.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunwoda.demo.dao.UserDao;
import com.sunwoda.demo.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Description:
 *
 * @author shiguorang
 * @date 2021-03-17 16:40:50
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获取主身份信息
        String username = (String) principalCollection.getPrimaryPrincipal();
//        查询权限信息
        List<User> user = userDao.getRole(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        user.forEach(one -> {
//            添加用户角色权限
            authorizationInfo.addRole(one.getRole());
//            添加用户操作权限
            List<User> list = userDao.getPermission(one.getId());
            list.forEach(entity -> {
                authorizationInfo.addStringPermission(entity.getPerms());
            });
        });
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", userName);
        User user = userDao.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}
